const app = getApp();

Page({
  data: {
    post: {},
    showContact: false,
    isFavorited: false,
    loadingFavorite: false,
    isMyPost: false,
    loading: false
  },

  onLoad(options) {
    this.postId = options.id;
    console.log('Post detail loaded, ID:', this.postId);
    this.loadPostDetail();
    this.checkFavoriteStatus();
  },

  onShow() {
    if (this.postId && app.globalData.userInfo) {
      this.checkFavoriteStatus();
      this.loadPostDetail();
    }
  },

  async loadPostDetail() {
    this.setData({ loading: true });
    
    try {
      console.log('Loading post detail...');
      const post = await app.request(`/posts/${this.postId}`, 'GET');
      console.log('Post detail loaded:', post);
      
      const isMyPost = post.author && post.author._id === app.globalData.userInfo?.id;
      
      this.setData({ 
        post,
        isMyPost,
        loading: false
      });
    } catch (error) {
      console.error('Load post detail error:', error);
      this.setData({ loading: false });
      wx.showToast({ title: '加载失败', icon: 'none' });
    }
  },

  async checkFavoriteStatus() {
    if (!app.globalData.userInfo) {
      console.log('Not logged in, skipping favorite check');
      return;
    }
    
    try {
      console.log('Checking favorite status for post:', this.postId);
      const result = await app.request(`/favorites/check/${this.postId}`, 'GET');
      console.log('Favorite status:', result.isFavorited);
      this.setData({ isFavorited: result.isFavorited });
    } catch (error) {
      console.error('Check favorite status error:', error);
    }
  },

  async onToggleFavorite() {
    if (!app.globalData.userInfo) {
      wx.showToast({ 
        title: '请先登录', 
        icon: 'none',
        success: () => {
          setTimeout(() => {
            wx.navigateTo({ url: '/pages/user/login/login' });
          }, 1500);
        }
      });
      return;
    }

    if (this.data.loadingFavorite) {
      return;
    }

    this.setData({ loadingFavorite: true });

    try {
      if (this.data.isFavorited) {
        console.log('Removing favorite...');
        await app.request(`/favorites/${this.postId}`, 'DELETE');
        this.setData({ isFavorited: false });
        wx.showToast({ 
          title: '取消收藏', 
          icon: 'success',
          duration: 1500
        });
      } else {
        console.log('Adding favorite...');
        await app.request(`/favorites/${this.postId}`, 'POST');
        this.setData({ isFavorited: true });
        wx.showToast({ 
          title: '收藏成功', 
          icon: 'success',
          duration: 1500
        });
      }
    } catch (error) {
      console.error('Toggle favorite error:', error);
      wx.showToast({ 
        title: error.error || '操作失败', 
        icon: 'none',
        duration: 2000
      });
    } finally {
      this.setData({ loadingFavorite: false });
    }
  },

  onToggleContact() {
    if (!app.globalData.userInfo) {
      wx.navigateTo({ url: '/pages/user/login/login' });
      return;
    }
    this.setData({ showContact: !this.data.showContact });
  },

  async onApplyFoster() {
    if (!app.globalData.userInfo) {
      wx.navigateTo({ url: '/pages/user/login/login' });
      return;
    }

    if (this.data.isMyPost) {
      wx.showToast({ title: '不能申请自己的帖子', icon: 'none' });
      return;
    }

    try {
      wx.showLoading({ title: '申请中...' });
      
      const result = await app.request(`/posts/${this.postId}/apply`, 'POST');
      
      wx.hideLoading();
      wx.showToast({ 
        title: '申请成功', 
        icon: 'success',
        success: () => {
          setTimeout(() => {
            this.loadPostDetail();
          }, 1500);
        }
      });
    } catch (error) {
      wx.hideLoading();
      console.error('Apply foster error:', error);
      wx.showToast({ title: error.error || '申请失败', icon: 'none' });
    }
  },

  onPayment() {
    if (!app.globalData.userInfo) {
      wx.navigateTo({ url: '/pages/user/login/login' });
      return;
    }
    
    if (!this.data.isMyPost) {
      wx.showToast({ title: '只有寄养人可以支付', icon: 'none' });
      return;
    }

    if (!this.data.post.fosterUser) {
      wx.showToast({ title: '暂无收养人申请', icon: 'none' });
      return;
    }
    
    wx.navigateTo({
      url: `/pages/payment/payment?postId=${this.postId}&amount=${this.data.post.price}`
    });
  },

  async onCompleteFoster() {
    if (!app.globalData.userInfo) {
      wx.navigateTo({ url: '/pages/user/login/login' });
      return;
    }

    const isAuthor = this.data.isMyPost;
    const isFosterUser = this.data.post.fosterUser && 
                         this.data.post.fosterUser._id === app.globalData.userInfo.id;

    if (!isAuthor && !isFosterUser) {
      wx.showToast({ title: '无权操作', icon: 'none' });
      return;
    }

    try {
      wx.showLoading({ title: '确认中...' });
      
      await app.request(`/posts/${this.postId}/complete`, 'POST');
      
      wx.hideLoading();
      wx.showToast({ 
        title: '寄养已完成', 
        icon: 'success',
        success: () => {
          setTimeout(() => {
            this.loadPostDetail();
          }, 1500);
        }
      });
    } catch (error) {
      wx.hideLoading();
      console.error('Complete foster error:', error);
      wx.showToast({ title: error.error || '操作失败', icon: 'none' });
    }
  },

  onStartChat() {
    if (!app.globalData.userInfo) {
      wx.navigateTo({ url: '/pages/user/login/login' });
      return;
    }
    
    const post = this.data.post;
    if (!post || !post.author) {
      wx.showToast({ title: '帖子信息错误', icon: 'none' });
      return;
    }

    console.log('Starting chat with author:', post.author);
    
    if (post.author._id === app.globalData.userInfo.id) {
      wx.showToast({ title: '不能和自己聊天', icon: 'none' });
      return;
    }

    wx.navigateTo({
      url: `/pages/chat/chat?toUserId=${post.author._id}&toUserName=${post.author.username}&postId=${this.postId}`
    });
  },

  onViewPayment() {
    wx.navigateTo({ url: '/pages/payment/history/history' });
  },

  onEditPost() {
    wx.showToast({ title: '编辑功能开发中', icon: 'none' });
  },

  onRate() {
    wx.showToast({ title: '评价功能开发中', icon: 'none' });
  },

  formatTime(dateString) {
    if (!dateString) return '';
    
    const date = new Date(dateString);
    const now = new Date();
    const diff = now - date;
    const minutes = Math.floor(diff / 60000);
    const hours = Math.floor(diff / 3600000);
    const days = Math.floor(diff / 86400000);

    if (minutes < 60) {
      return `${minutes}分钟前`;
    } else if (hours < 24) {
      return `${hours}小时前`;
    } else if (days < 7) {
      return `${days}天前`;
    } else {
      return date.toLocaleDateString();
    }
  },

  formatDate(dateString) {
    if (!dateString) return '';
    return new Date(dateString).toLocaleDateString();
  }
});